<!DOCTYPE html>
<html style="height: 100%;">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>模板管理页面</title>
<!-- 设置网页图标 -->
<link rel="shortcut icon" href="../../images/favicon.png" type="image/x-icon" />
<!-- 引入CSS -->
<link rel="stylesheet" href="../../layui/css/layui.css">
<link rel="stylesheet" href="../../css/codemirror.css">
<link rel="stylesheet" href="../../css/dracula.css">
<link rel="stylesheet" href="../../css/simplescrollbars.css">
<link rel="stylesheet" href="../../css/matchesonscrollbar.css">
<link rel="stylesheet" href="../../css/dialog.css">
<link rel="stylesheet" href="../../css/show-hint.css">
<!-- 引入JS -->
<script src="../../layui/layui.js"></script>
<script src="../../js/codemirror.js"></script>
<script src="../../js/velocity.js"></script>
<script src="../../js/active-line.js"></script>
<script src="../../js/simplescrollbars.js"></script>
<script src="../../js/search.js"></script>
<script src="../../js/matchesonscrollbar.js"></script>
<script src="../../js/searchcursor.js"></script>
<script src="../../js/jump-to-line.js"></script>
<script src="../../js/dialog.js"></script>
<script src="../../js/anyword-hint.js"></script>
<script src="../../js/show-hint.js"></script>

<script type="text/javascript">
layui.use([ 'layer','element'], function() {
	var $ = layui.$,layer = layui.layer,element = layui.element,router = layui.router();
	/* 获取模板ID */
	var setid=router.search.setid;
	/* 存储在线编辑器数组对象 */
	var models=[];
	/* 编辑器最大字数 */
	var maxlength= 999999;
	/* 最大长度提示变量 用于解决频繁提示 */
	var maxlengthTips=true;
	/* 进入页面时获取此模板集的自定义模板 */
	$.ajax({
		type : "GET",
		url : "/template/templates?page=1&rows=500&templateSetId="+setid,
		async : true,
		dataType : "json",
		success : function(data) {
			/* 返回成功处理数据 */
			if (data.code == 200) {
				filldata(data);
			} else {
				/* 加载默认模板 */
				$.ajax({
					type : "GET",
					url : "/template/default/templates",
					async : true,
					dataType : "json",
					success : function(data) {
						/* 返回成功处理数据 */
						if (data.code == 200) {
							filldata(data);
						}else{
							layer.msg('没有默认模板数据');
						}
					}
				});
			}
		}
	});
	/* 填充数据方法 */
	function filldata(data){
		$.each(data.data.rows, function(idx, row) {
			var obj=new Object();
			if(idx==0){
				$('#model_tabs').append('<li class="layui-this" lay-id="'+row.templateName+'">'+row.templateName+'</li>');
				$('#model_codes').append('<div class="layui-tab-item layui-show" style="height: 100%;"><textarea id="'+row.templateName+'">'+row.content+'</textarea><div>');
			}else{
				$('#model_tabs').append('<li lay-id="'+row.templateName+'">'+row.templateName+'</li>');
				$('#model_codes').append('<div class="layui-tab-item" style="height: 100%;"><textarea id="'+row.templateName+'">'+row.content+'</textarea><div>');
			}
			/* 在线编辑器 */
		   	obj.editor = CodeMirror.fromTextArea(document.getElementById(row.templateName), {
		        theme: "dracula",
		        scrollbarStyle:"simple",
		        lineNumbers: true,
		        styleActiveLine: true,
		        extraKeys: {
		        	"Alt-/": "autocomplete",
		        	"Ctrl-F": "findPersistent",
		        	"Ctrl-D" : "deleteLine",
		        	"Ctrl-S" : function(){
		        		saveData();
		        	},
		        	"Esc" : function(){
		        		window.history.back(-1);
		        	}
		         },
		        indentUnit: 4,
		        maxlength : maxlength,
		        mode: "text/velocity"
		     });
		   	obj.editor.setSize('100%', '100%');
		   	obj.editor.on("beforeChange", enforceMaxLength);
		   	obj.name=row.templateName;
		   	obj.sort=idx;
		   	models.push(obj);
		});
		/* 一定初始化一次不然事件会失效 */
		models[0].editor.focus();
		models[0].editor.setCursor(models[0].editor.lineCount(), 0);
		layui.element.init();
	}
	/* 解决编辑器内容过长内存溢出问题 */
	var enforceMaxLength = function(cm, change) {
	    var maxLength = cm.getOption("maxlength");
	    if (maxLength && change.update) {
	        var str = change.text.join("\n");
	        var delta = str.length-(cm.indexFromPos(change.to) - cm.indexFromPos(change.from));
	        if (delta <= 0) { return true; }
	        delta = cm.getValue().length+delta-maxLength;
	        if (delta > 0) {
	            str = str.substr(0, str.length-delta);
	            change.update(change.from, change.to, str.split("\n"));
	            if(maxlengthTips){
	            	maxlengthTips=false;
	            	layer.msg('编辑器内容已超过'+maxlength+'字符,无法继续输入!', {icon: 5});
					setTimeout(function(){
						maxlengthTips=true;
					},1000);
				}
	        }
	    }
	    return true;
	}
	/* 设置选项卡点击事件 */
	element.on('tab(code-tabs)', function(data){
		/* 自动刷新一次保证不错位并聚焦 */
		models[data.index].editor.refresh();
		models[data.index].editor.focus();
		models[data.index].editor.setCursor(models[data.index].editor.lineCount(), 0);
	});
	/* 保存按钮 */
	$(document).on('click', '#btn_save', function(){
		saveData();
	});
	/* 保存数据 */
	var isClick = true;
	var tips = true;
	var timeout=5;
	function saveData(){
		if(isClick) {
			isClick=false;
			/* 组装数据 */
			var temps=[];
			$.each(models,function(idx,data){
				var obj=new Object();
				obj.templateSetId=setid;
				obj.templateName=data.name;
				obj.content=data.editor.getValue();
				obj.sort=data.sort;
				temps.push(obj);
			});
			/* 异步保存数据 */
			$.ajax({
				type : "POST",
				url : "/template/templates",
				async : true,
				data: JSON.stringify(temps),
				contentType:"application/json",
				dataType : "json",
				success : function(data) {
					/* 返回成功处理数据 */
					if (data.code == 200) {
						layer.msg('保存成功', {icon: 1});
					}else{
						layer.msg('保存失败', {icon: 2});
					}
				}
			});
			setTimeout(function(){
				isClick=true;
			},timeout*1000);
		}else{
			if(tips){
				tips=false;
				layer.msg('保存操作太频繁,每'+(timeout)+'秒只能保存一次请稍后重试!', {icon: 4});
				setTimeout(function(){
					tips=true;
				},1000);
			}
		}
	}
	/* 返回按钮 */
	$(document).on('click', '#btn_back', function(){
		/* 返回 */
		window.history.back(-1);
	});
	/* 提示信息 */
	$(document).on('click', '#btn_guide', function(){
		layer.open({type: 1,shade: false,title: false,content: $('#tips')});
	});
});
</script>
</head>
<body style="height: 100%;">
<div class="layui-tab layui-tab-brief" style="height: 100%;" lay-filter="code-tabs">
  <ul class="layui-tab-title" id="model_tabs">
  	<button type="button" class="layui-btn layui-btn-warm" id="btn_back" style="float: right;margin-right: 10px;"><i class="layui-icon">&#xe603;</i>&nbsp;返回</button>
  	<button type="button" class="layui-btn" id="btn_save" style="float: right;margin-right: 10px;"><i class="layui-icon">&#xe66c;</i>&nbsp;保存</button>
  </ul>
  <div class="layui-tab-content" id="model_codes" style="height: 90%;"></div>
</div>
</body>
</html>